﻿using AutoMapper;
using AutoMapper.QueryableExtensions;
using Microsoft.EntityFrameworkCore;
using WebApiFirst.Entity;
using WebApiFirst.IService;
using WebApiFirst.Model.Req;
using WebApiFirst.Model.Res;

namespace WebApiFirst.Service
{
    public class StudentService : IStudentService
    {
        private readonly AppDbContext db;
        private readonly IMapper mapper;
        private readonly ILogger logger;

        public StudentService(AppDbContext db,IMapper mapper) {
            this.db = db;
            this.mapper = mapper;
            //his.logger = logger;
        }

        public async Task<int> Add(AddReq addReq)
        {
            var entity = mapper.Map<Student>(addReq);
            db.Students.Add(entity);
            db.Entry(entity);
            await db.SaveChangesAsync();
            return entity.Id;
        }

        public async Task<int> Delete(int id)
        {
            var entity = db.Students.Where(p=>p.Id == id).FirstOrDefault();
            if(entity == null)
            {
                return 0;
            }
            else
            {
                entity.IsDelete = true;
                await db.SaveChangesAsync();
                return id;
            }
        }

        /// <summary>
        /// 获取所有列表
        /// </summary>
        /// <returns></returns>
        public async Task<List<StudentRes>> GetList()
        {
            logger.LogInformation("执行:GetList");
            var list = await db.Students.ProjectTo<StudentRes>(mapper.ConfigurationProvider).ToListAsync();
            return list.ToList();
        }

        /// <summary>
        /// 客户端评估
        /// </summary>
        /// <returns></returns>
        public async Task<IEnumerable<StudentRes>> GetListClientApprove()
        {
            // 生成的sql 如下
            //SELECT[t].[Id], [t].[Email], [t].[IsDelete], [t].[Name], [t].[Phone], [t].[PhoneNumber]
            //FROM[T_Student] AS[t]  WHERE[t].[IsDelete] = CAST(0 AS bit) AND[t].[Id] > 0

            IEnumerable<Student> result = db.Students.Where(p=> p.Id > 0);
            var list = result.Select(p => new StudentRes() { Id = p.Id, Name = p.Name?.Substring(0, 1), Email = p.Email, Phone = p.Phone?.Replace("1", "*") });
            return await Task.FromResult( list.ToList());
        }

        /// <summary>
        /// 服务端评估
        /// </summary>
        /// <returns></returns>
        public async Task<IEnumerable<StudentRes>> GetListServerApprove()
        {
            // 生成sql如下
            //SELECT [t].[Id], SUBSTRING([t].[Name], 0 + 1, 1) AS [Name], [t].[Email], REPLACE([t].[Phone], N'1', N'*') AS [Phone]
            //FROM[T_Student] AS[t] WHERE[t].[IsDelete] = CAST(0 AS bit) AND[t].[Id] > 0

            IQueryable<Student> queryable = db.Students.Where(p => p.Id > 0);
            var list = queryable.Select(p=> new StudentRes() { Id = p.Id,Name = p.Name.Substring(0,1), Email= p.Email, Phone=p.Phone.Replace("1","*")});

            return  await list.ToListAsync();
        }

        /// <summary>
        /// 循环遍历
        /// </summary>
        /// <returns></returns>
        public async Task ForeachStudents()
        {
            var stuListQueryable = db.Students.Where(p=>p.Id >0);
            var list = stuListQueryable.ToList();
            foreach (var item in list)
            {
                Console.WriteLine(item.Name);
                await Task.Delay(100);
            }
        }

        /// <summary>
        /// 获取对象并利用AutoMapper 映射结果对象中
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<StudentRes?> GetStudent(int id)
        {
            var result = await db.Students.ProjectTo<StudentRes>(mapper.ConfigurationProvider).Where(p => p.Id == id).FirstOrDefaultAsync();
            return result;
        }

       /// <summary>
       /// 更新对象通过autoMapper进行请求参数映射；
       /// </summary>
       /// <param name="id"></param>
       /// <param name="updateReq"></param>
       /// <returns></returns>
        public async Task<bool> Update(int id,  UpdateReq updateReq)
        {
            var entity = await db.Students.Where(p => p.Id == id).FirstOrDefaultAsync();

            if (entity == null)
            {
                return false;
            }
            else
            {
                entity = mapper.Map(updateReq, entity);
                var entry = db.Entry(entity);
                var view = entry.DebugView.LongView;
                await db.SaveChangesAsync();
                return true;
            }
        }


    }
}
